<template>
    <div class="bg">
        <div class="header">
            <router-link to="/my" class="header-btnLeft"><img src="../assets/back-btn.png"></router-link>
            <h1 class="header-title">我的订单</h1>
            <div class="header-btnRight"></div>
        </div>
        <div class="tab">
            <div class="tab-menu">
                <div :class="tabArr.curHdIndex == index ? 'active' : ''" v-for="(item,index) in tabArr.data"
                     @click="tabFun(index,index)">{{item}}
                </div>
            </div>
            <div class="tab-body">
                <div class="tab-body-item active">
                    <div class="list">
                        <div class="list-item" v-for="(item,index) in orderArr">
                            <div class="list-item-head">
                                <div class="list-item-head-num">订单编号：{{item.order_no}}</div>
                                <div class="list-item-head-pay">
                                <span v-if="item.finished_condition==1">
                                    <span v-if="item.order_status==1">未完善</span>
                                </span>
                                    <span v-else>{{statusArr[item.order_status]}}</span>

                                </div>
                            </div>
                            <div class="list-item-info">

                                <!--拼游-->
                                <router-link :to="'/GroupList'" v-if="item.orderType=='CarPool'" class="list-item-info-title">
                                    {{item.goods_name}}
                                </router-link>
                                <!--定制-->
                                <router-link :to="'/my-order-detail/'+item.order_no" v-else-if="item.orderType=='CustomMade'" class="list-item-info-title">
                                    {{item.goods_name}}
                                </router-link>
                                <div v-else>
                                    <router-link :to="'/show/'+item.goods_id" class="list-item-info-title"
                                                 v-if="item.types!='KBX'">
                                        {{item.goods_name}}
                                    </router-link>
                                    <a v-else :href="item.url" class="list-item-info-title">
                                        {{item.goods_name}}
                                    </a>
                                </div>
                                <div class="list-item-info-data">出游时间：{{item.travel_date}}</div>
                                <div class="list-item-info-num" v-if="item.orderType !=='CarPool'">数量：
                                    <span v-for="item2 in item.person">
                                    {{item2.person_name}}×{{item2.person_num}}
                                </span>
                                </div>
                                <div class="list-item-info-num" v-if="item.orderType =='CarPool'">数量：
                                    <span>
                                    1
                                   </span>
                                </div>
                                <!-- <div class="list-item-info-num">备注：{{item.remarks}}</div> -->
                                <div class="list-item-info-price">¥
                                    <span v-if="item.fold_money || item.fold_money >= 0">{{item.fold_money}}</span>
                                    <span v-else="item.original_money">{{item.original_money}}</span>
                                </div>
                            </div>

                            <div v-if="item.types=='KBX'">
                                <div class="list-item-btn">
                                    <div></div>
                                    <div>
                                        <span class="btn list-item-btn-cancel" v-if="item.order_status==1"  @click="delOtherOrder(item,index)">取消</span>
                                        <a :href="item.url">
                                            <span class="btn list-item-btn-primary"  v-if="item.order_status==1">立即支付</span>
                                            <span class="btn list-item-btn-success" v-if="item.order_status==2">已支付</span>
                                            <span class="btn list-item-btn-cancel" v-if="item.order_status==3">待评价</span>
                                            <span class="btn list-item-btn-cancel" v-if="item.order_status==4">已评价</span>
                                            <span class="btn list-item-btn-cancel" v-if="item.order_status==5">退款申请中</span>
                                            <span class="btn list-item-btn-cancel" v-if="item.order_status==6">已取消</span>
                                            <span class="btn list-item-btn-cancel" v-if="item.order_status==7">已过期</span>
                                            <span class="btn list-item-btn-cancel" v-if="item.order_status==8">已退款</span>
                                            <span class="btn list-item-btn-cancel" v-if="item.order_status==9">拒绝退款</span>
                                        </a>
                                        <router-link v-if="item.order_status!=1 && item.order_status!=6 && item.order_status!=7" :to="'/my-order-detail/'+item.order_no" class="btn list-item-btn-cancel">订单详情</router-link>
                                    </div>

                                </div>
                            </div>
                            <div v-else>
                                <!-- finished_condition 订单完成状态 0表示完成 1表示未完成' -->
                                <div class="list-item-btn btn2" v-if="item.finished_condition==1">
                                    <span class="btn list-item-btn-cancel" @click="cancelOrder(item,index)"
                                          v-if="item.order_status==1 || item.order_status==7">删除</span>
                                     <span v-if="item.orderType !=='CarPool'">
                                        <router-link :to="{path:'/show-order',query:{order_id:item.order_id,goods_id:item.goods_id,order_no:item.order_no,orderType:item.orderType}}"
                                                     style='display:inline-block;' v-if="item.order_status==1"
                                                     class="btn list-item-btn-cancel">完善
                                        </router-link>
                                    </span>
                                    <span v-if="item.orderType =='CarPool'">
                                        <router-link :to="{path:'/GroupShowOrder',query:{order_id:item.order_id,goods_id:item.goods_id,order_no:item.order_no,orderType:item.orderType,line_id:item.line_id}}"
                                                     style='display:inline-block;' v-if="item.order_status==1"
                                                     class="btn list-item-btn-cancel">完善
                                        </router-link>
                                    </span>
                                    <span class="btn list-item-btn-gray" v-if="!item.isdelete && item.order_status==7">已过期</span>
                                </div>
                                <div class="list-item-btn" v-if="item.finished_condition!=1">
                                    <div>
                                        <div class="list-item-time"
                                             v-if="(countDownList[index].min!='00' || countDownList[index].sec!='00') && item.order_status==1">
                                            支付时间：{{countDownList[index].min}}分{{countDownList[index].sec}}秒
                                        </div>
                                    </div>
                                    <div>
                                        <span class="btn list-item-btn-cancel" @click="cancelOrder(item,index)"
                                              v-if="item.order_status==1 || item.order_status==7">删除</span>
                                        <span v-if="item.orderType !=='CarPool'">
                                            <router-link v-if="(countDownList[index].min!='00' || countDownList[index].sec!='00') && item.order_status==1" :to="'/my-order-detail-unpaid?order_no='+item.order_no" class="btn list-item-btn-cancel">订单详情</router-link>
                                        </span>
                                        <span v-if="item.orderType =='CarPool'">
                                            <router-link v-if="(countDownList[index].min!='00' || countDownList[index].sec!='00') && item.order_status==1" :to="'/GroupShowOrder-detail-unpaid?order_no='+item.order_no" class="btn list-item-btn-cancel">订单详情</router-link>
                                        </span>
                                        <span class="btn list-item-btn-primary" @click="choosePayType(item,index)"
                                              v-if="(!item.isdelete && item.order_status==1 && countDownList[index]) && ( countDownList[index].min!='00' || countDownList[index].sec!='00')">立即支付</span>
                                        <span class="btn list-item-btn-success"
                                              v-if="!item.isdelete   && item.order_status==2">已支付</span>
                                        <span class="btn"
                                              :class="item.refund_status==0 ? 'list-item-btn-primary' : 'list-item-btn-gray'"
                                              v-if="!item.isdelete  && item.order_status==2 || item.order_status==8"
                                              @click="refundPay(item,item.refund_status)">
                                            <span v-if="item.refund_status==0">申请退款</span>
                                            <span v-else-if="item.refund_status==1">退款审核</span>
                                            <span v-else-if="item.refund_status==2">退款成功</span>
                                            <span v-else-if="item.refund_status==3">退款拒绝</span>
                                        </span>
                                        <span class="btn list-item-btn-primary"
                                              @click="commentOrder(item.order_id,item.goods_id)"
                                              v-if="!item.isdelete   && item.order_status==3">去评价</span>
                                        <span class="btn list-item-btn-gray"
                                              v-if="!item.isdelete   && item.order_status==4">已评价</span>
                                        <span class="btn list-item-btn-gray"
                                              v-if="(!item.isdelete   && item.order_status==7) && (countDownList[index].min=='00' && countDownList[index].sec=='00')">已过期</span>
                                        <router-link :to="'/show/'+item.goods_id" class="btn list-item-btn-primary"
                                                     v-if="!item.isdelete   && item.order_status==7">购买
                                        </router-link>
                                        <span class="btn list-item-btn-cancel2" v-if="item.isdelete || item.order_status==6">已取消</span>
                                        <router-link v-if="item.order_status==2 || item.order_status==3 ||item.order_status==4" :to="'/my-order-detail/'+item.order_no" class="btn list-item-btn-cancel">订单详情</router-link>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <mt-actionsheet
        :actions="payActions"
        v-model="payState">
        </mt-actionsheet>
    </div>
</template>

<script>
    import { Card, createToken,cardElement, } from 'vue-stripe-elements-plus';
    import {Toast, MessageBox,Indicator} from "mint-ui"
    import wxShare from "../store/wxShare"

    export default {
        name: "My-ticket",
        components:{
            Card
        },
        data() {
            return {
                tabArr: {
                    data: ['全部', '待支付', '待出行', '待评价'],
                    curHdIndex: 0,
                },
                orderArr: [],
                status: '', //订单状态
                statusArr: ['', '待付款', '待使用', '待评价', '已评价', '退款中', '已取消', '已过期'],
                countDownList: [],
                totalPricePay:"",
                orderIndex:"",
                order_id:"",
                payState:false,
                payActions:[],
                payBtnState:false,
                orderType:"",
                order_no:"",
                stripePayInfo:{}
            }
        },
        methods: {
            // 评论
            commentOrder(order_id, goods_id) {
                this.$router.push('/comment-add/' + order_id + '/' + goods_id)
            },
            // 删除订单
            cancelOrder: function (item, index) {
                var _that = this;

                MessageBox({
                    title: '提示',
                    message: '是否删除订单？',
                    confirmButtonText:'删除',
                    showCancelButton: true
                }).then(res=>{
                    if(res=='confirm'){
                        _that.axios.post('wap/member/delorder', {
                                order_id: item.order_id,
                                orderType: item.orderType,
                                order_no: item.order_no
                            }
                        ).then(res => {
                            var orderArr = _that.orderArr;
                            orderArr.splice(index, 1);
                            _that.orderArr = orderArr;
                            Toast({message: res.msg, duration: 1500});
                        }).catch(err => console.log(err));
                    }
                });
            },
            // 删除三方订单
            delOtherOrder: function (item, index) {
                var _that = this;
                MessageBox({
                    title: '提示',
                    message: '是否取消订单？',
                    confirmButtonText:'确定',
                    showCancelButton: true
                }).then(res=>{
                    if(res=='confirm'){
                        _that.axios.post('wap/Kbxcoupon/KBXremoveOrder', {order_id: item.order_id,
                                orderType: item.orderType,
                                order_no: item.order_no})
                            .then(res => {
                                var orderArr = _that.orderArr;
                                orderArr.splice(index, 1);
                                _that.orderArr = orderArr;
                                Toast({message: res.msg, duration: 1500});
                            })
                            .catch(err => console.log(err));
                    }
                });
            },


            timeFormat(param) {//小于10的格式化函数
                return param < 10 ? '0' + param : param;
            },
            countDown() {
                // 获取当前时间，同时得到活动结束时间数组
                let newTime = new Date().getTime();
                let endTimeList = this.actEndTimeList;
                let countDownArr = [];

                // 对结束时间进行处理渲染到页面
                endTimeList.forEach(o => {
                    let endTime = new Date(o).getTime() + (1800 * 1000); //结束时间+30分钟
                    let obj = null;
                    // 如果活动未结束，对时间进行处理
                    if (endTime - newTime > 0) {
                        let time = (endTime - newTime) / 1000;
                        // 获取天、时、分、秒
                        //let day = parseInt(time / (60 * 60 * 24));
                        //let hou = parseInt(time % (60 * 60 * 24) / 3600);
                        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
                        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
                        obj = {
                            //day: this.timeFormat(day),
                            //hou: this.timeFormat(hou),
                            min: this.timeFormat(min),
                            sec: this.timeFormat(sec)
                        }
                    } else {//活动已结束，全部设置为'00'
                        obj = {
                            // day: '00',
                            // hou: '00',
                            min: '00',
                            sec: '00'
                        }
                    }
                    countDownArr.push(obj);
                })
                // 渲染，然后每隔一秒执行一次倒计时函数
                //console.log(countDownArr);
                this.countDownList = countDownArr;
                setTimeout(this.countDown, 1000);
            },
            tabFun(val, status) {
                this.tabArr.curHdIndex = val;
                this.status = status;
                this.getData();
            },
            getData() {
                let _that = this;
                var params = {};
                if (_that.status) {
                    params.status = _that.status;
                }
                _that.axios.post('/wap/member/order', params,true)
                    .then(res => {
                        _that.orderArr = res.data
                        let endTimeList = [];
                        // 结束时间参数提成一个单独的数组
                        _that.orderArr.forEach(o => {
                            if (o.types != "KBX" && !o.isdelete && o.order_status == 1 && o.creattime) {
                                endTimeList.push(o.creattime.replace(/-/g, '/'))
                            } else {
                                endTimeList.push({})
                            }
                        })
                        _that.actEndTimeList = endTimeList;
                        // 执行倒计时函数
                        _that.countDown();
                    })
                    .catch(err => console.log(err));
            },
            choosePayType(item,index) {
                this.orderIndex = index;
                this.totalPricePay = item.fold_money;
                this.goods_id = item.goods_id;
                this.order_id = item.order_id;
                this.orderType = item.orderType;
                this.order_no = item.order_no;
                this.payState = true;
                this.stripePayInfo.moneyArr = item.moneyArr;
                this.stripePayInfo.orderData = {
                    goods_id:this.goods_id,
                    order_id:this.order_id,
                    orderType:this.orderType,
                    order_no:this.order_no,
                }
            },
          beginPay(index) {

            let fromApp = 0;
            if (this.$store.state.appNestState) {
              fromApp = 1;
            }

            let order_id = this.orderArr[index].order_id;
            let postData = {
              order_id: order_id,
              order_no: this.order_no,
              orderType: this.orderType
            };

            let appid = window.localStorage.appid;
            if (fromApp && appid && appid.length > 0) {
              postData.appid = appid;
            }

            this.axios.post('/wxpay', postData)
              .then(res => {
                if(!fromApp) {
                  var params = {
                    order_index: index,
                    appId: res.data.appId,
                    timeStamp: res.data.timeStamp,
                    nonceStr: res.data.nonceStr,
                    package: res.data.package,
                    paySign: res.data.paySign
                  };
                  this.wxPay(params);
                } else {
                  this.appWXPay(res.data);
                }
              })
              .catch(err => console.log(err));
          },
            // 微信支付
            wxPay(params) {
                var _that = this
                console.log(params)

                function onBridgeReady() {
                    console.log('onBridgeReady');
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest', {
                            "appId": params.appId,     //公众号名称，由商户传入
                            "timeStamp": params.timeStamp,  //时间戳，自1970年以来的秒数
                            "nonceStr": params.nonceStr, //随机串
                            "package": params.package,
                            "signType": "MD5",         //微信签名方式
                            "paySign": params.paySign //微信签名
                        },
                        function (res) {
                            if (res.err_msg == "get_brand_wcpay_request:ok") {
                                _that.$router.push({path:'/pay-success',query:{goods_id: _that.orderArr[params.order_index].goods_id,order_id:  _that.orderArr[params.order_index].order_id}});
                                _that.orderArr[params.order_index].order_status = 2
                            }
                        });
                }

                if (typeof WeixinJSBridge == "undefined") {
                    if (document.addEventListener) {
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                    } else if (document.attachEvent) {
                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                    }
                } else {
                    onBridgeReady();
                }
            },

              appWXPay(params) {
                let that = this;

                let data = {
                  command: 'wechatPay',
                  content: {
                    action:'wechatPay',
                    orderId: that.order_id,
                    goodsId: that.goods_id,
                    partnerId: params.partnerid,
                    prepayId: params.prepayid,
                    timeStamp: params.timestamp,
                    package: params.package,
                    nonceStr: params.noncestr,
                    sign: params.sign
                  }
                };
                window.postMessage(JSON.stringify(data))
              },
            // 退款
            refundPay(item, refund_status) {
                if (refund_status == 0) {
                    MessageBox({
                        title: '提示',
                        message: '提交退款申请后，将由服务管家审核是否符合退款条件，以及可退金额。',
                        confirmButtonText:'确定',
                        showCancelButton: true
                    }).then(res=>{
                        if(res=='confirm'){
                            this.axios.post('/wap/member/refund', {order_id: item.order_id,
                                orderType: item.orderType,
                                order_no: item.order_no})
                                .then(res => {
                                    Toast({message: '已提交申请，请等待审核', duration: 1500});
                                    this.getData();
                                })
                                .catch(err => console.log(err));
                        }
                    });
                } else {
                    Toast({message: '不符合申请退款条件', duration: 1500});
                }
            },
            share() {
                wxShare({title: '我的订单', debug: false}, function () {
                    console.log('分享成功')
                });
            }
        },
        created(){
            if(!sessionStorage.reloaded){
                sessionStorage.reloaded = true;
                location.reload();
            }
        },
        mounted() {
            let _that = this;
            this.getData();
            this.share();
            this.payActions = [
                {
                    name:"微信支付",
                    method:function(){
                        _that.beginPay(_that.orderIndex);
                    }
                },
                {
                    name:"信用卡支付",
                    method:function(){
                        _that.$router.push({path:'/stripe-pay',query: { order_id: _that.order_id,goods_id: _that.goods_id,orderType:_that.orderType,order_no:_that.order_no,totalPricePay:_that.totalPricePay}})
                    }
                }
            ];
        },
        beforeRouteLeave(to, from, next) {
            if (to.name == "stripe-pay") {
                sessionStorage.stripePayInfo = JSON.stringify(this.stripePayInfo);
                next();
            }else{
                next();
            }
        }
    }
</script>

<style lang="scss" scoped>
    @import "../assets/base";

    .h30 {
        height: rpx(30);
        background: $bgcolor1
    }

    .h120 {
        height: rpx(200);
        background: $bgcolor1;
    }

    .bg {
        background: $bgcolor1;
        min-height: 100%;
    }

    .header {
        display: flex;
        align-items: center;
        padding: rpx(30);
        justify-content: space-between;
        background: $color0;
        &-btnLeft {
            width: rpx(64);
            height: rpx(64);
            padding-top: rpx(16);
            img {
                width: rpx(32);
                height: rpx(32);
            }
        }
        &-btnRight:after {
            display: block;
            content: ' ';
            width: rpx(64);
            height: rpx(64);
        }
        &-title {
            flex: 1;
            font-size: rpx(36);
            text-align: center;
            font-weight: normal;
        }
    }

    .tab {
        &-menu {
            display: flex;
            background: $color0;
            &-badge {
                top: rpx(15);
                right: rpx(10);
                position: absolute;
                background: $color3;
                font-size: rpx(20);
                width: rpx(30);
                height: rpx(30);
                line-height: rpx(30);
                text-align: center;
                color: $color0;
                border-radius: 100%;
            }
        }
        &-menu div {
            flex: 1;
            position: relative;
            padding: rpx(30) rpx(20);
            text-align: center;
            color: $color5;
            font-size: rpx(36);
            border-bottom: solid $color2 rpx(4);
        }

        &-menu .active {
            color: $color3;
            border-bottom: solid $color3 rpx(4);
        }

        &-body {
            &-item {
                display: none;
            }
            &-item.active {
                display: block;
            }
        }
    }

    .list {
        &-item {
            margin-top: rpx(30);
            background: $color0;
            &-head {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: rpx(20) rpx(30);
                &-num {
                    font-size: rpx(24);
                    color: $color5;
                }
                &-pay {
                    font-size: rpx(24);
                    color: $color3;
                }
            }
            &-info {
                position: relative;
                padding: rpx(30);
                border-top: solid 1px #F1F1F1;
                border-bottom: solid 1px #F1F1F1;
                background: #FFFBF2;
                &-title {
                    font-size: rpx(30);
                    line-height: 130%;
                }
                &-data {
                    padding-top: rpx(20);
                    font-size: rpx(24);
                    color: $color5;
                    line-height: 130%;
                }
                &-num {
                    font-size: rpx(24);
                    color: $color5;
                    width: 70%;
                    line-height: 130%;
                }
                &-price {
                    position: absolute;
                    right: rpx(30);
                    bottom: rpx(30);
                    font-size: rpx(40);
                    color: $color3;
                }
            }
            &-btn {
                display: flex;
                justify-content: space-between;
                padding: rpx(20) rpx(30);
                .btn {
                    display: inline-block;
                    margin-left: rpx(20);
                    padding: rpx(10) rpx(20);
                    border-radius: $radius6;
                    font-size: rpx(28);
                }

                &-primary {
                    background: $color3;
                    color: $color0;
                }
                &-gray {
                    background: $color5;
                    color: $color0;
                }
                &-success {
                    background: $color4;
                    color: $color0;
                }
                &-cancel {
                    border: solid 1px $color1;
                    color: $color1;
                }
                &-cancel2 {
                    border: solid 1px $color5;
                    color: $color5;
                }
                &.btn2 {
                    justify-content: flex-end;
                }
            }
            &-time {
                display: block;
                padding: rpx(30) 0 0;
                color: $color3;
                font-size: rpx(24);
            }
        }
    }

</style>
